﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EvincePayroll.Data;
using EvincePayroll.Utility;

namespace EvincePayroll.Logic
{
    public class EmployeeLogic:BaseLogic
    {
        public EmployeeLogic(string userId)
            : base(userId)
        { }


        //Send email method
        public string SendMailMethod(string emailId, string purpose, string subject, string message)
        {
            var toAddress = emailId;
            string body = "From: Admin \n";
            body += message;
            MailSending mail = new MailSending();
            mail.SendMail(toAddress, subject, body);
            return "";

        }


        public EmployeeData GetEmployeeDataByEmployeeId(string employeeId)
        {
            EmployeeData employee = null;
            if (!string.IsNullOrEmpty(employeeId))
                employee = db.GetEmployeeDataByEmployeeId(employeeId);
            return employee;
        }


        //Completed
        public EmployeeData AuthenticateUser()
        {
            try
            {
                return db.GetEmployeeDataByEmployeeId(_userCredentials.userId);
            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;
            }
        }

        //Completed
        public EmployeeData GetEmployeeData(string userId)
        {
            EmployeeData result = null;
            try
            {
                result= db.GetEmployeeDataList().Where(x=>x.Email.Equals(userId.Trim())).FirstOrDefault();
                var checkInStatus = db.GetAttendanceLogDataList().Where(x => x.EmployeeId.Equals(result.ID) && x.Date.Equals(DateTime.Today) && x.IsActive.Equals(true)).FirstOrDefault();
                if (checkInStatus != null)
                    result.CheckInStatus =Convert.ToInt32(checkInStatus.IsActive);
                
            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;
            }
            return result;
        }

        //Completed
        public bool AuthenticateLogin(string emailId,string password)
        {
            bool result = false;
            try
            {
                var employeeList = db.GetEmployeeDataList();
                if (employeeList != null)
                {
                    var isAuthenticated = employeeList.Where(x => x.Email.Equals(emailId) && x.Password.Equals(Cryptography.EncryptStringAES(password, "evincePassword")) && x.IsActive==1).FirstOrDefault();
                    if (isAuthenticated != null)
                    {
                        result = true;
                        isAuthenticated.IsOnline = true;
                        db.UpdateEmployee(isAuthenticated);
                    }
                }
                return result;
                //return db.AuthenticateLogin(emailId, password);
            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;
            }
        }

        //Completed
        public bool AuthenticateEmail(string emailId)
        {
            bool result = false;
            try
            {
                var employeeList = db.GetEmployeeDataList();
                if (employeeList != null)
                {
                    var employee = employeeList.Where(x => x.Email.Equals(emailId)).FirstOrDefault();
                    if (employee != null)
                    {
                        string message = string.Format("Your password is : {0}", Cryptography.DecryptStringAES(employee.Password, "evincePassword"));
                        string subject = "Forgoted password!";
                        SendMailMethod(employee.Email, Constants.EMAIL_ACTIVATION, subject, message);
                        result = true;
                    }
                }
                //return db.AuthenticateEmail(emailId);
            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;
            }
            return result;
        }


        //Completed
        public bool Logout(string emailId, string password)
        {
            bool result = false;
            try
            {
                var employeeList = db.GetEmployeeDataList();
                if (employeeList != null)
                {
                    var isAuthenticated = employeeList.Where(x => x.Email.Equals(emailId)).FirstOrDefault();
                    if (isAuthenticated != null)
                    {
                        result = true;
                        isAuthenticated.IsOnline = false;
                        db.UpdateEmployee(isAuthenticated);
                    }
                }
                return result;
                //return db.AuthenticateLogin(emailId, password);
            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;
            }
        }

        //Completed
        public List<EmployeeData> RegisterEmployee(EmployeeData employeeData)
        {
            List<EmployeeData> result = null;
            try
            {
                bool isCreated = db.CreateEmployee(employeeData);
                if (isCreated == true)
                {
                    result = db.GetEmployeeDataList();
                }
                //return db.RegisterEmployee(employeeData);
            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;
            }
            return result;
        }

        //Completed
        public List<EmployeeData> GetEmployeeList(string emailId)
        {
            try
            {
                return db.GetEmployeeDataList();
            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;
            }
        }
        //Completed
        public List<EmployeeData> GetEmployeeListForActivation(string emailId)
        {
            List<EmployeeData> result = null;
            try
            {
                var employeeList = db.GetEmployeeDataList();
                var userRoleList = db.GetUserRoleDataList();
                result=(from list in employeeList
                              join role in userRoleList on list.UserRoleId equals role.UserRoleId
                              select new EmployeeData{
                                  ID = list.ID,
                                  FirstName = list.FirstName,
                                  LastName = list.LastName,
                                  TemporaryAddress = list.TemporaryAddress,
                                  City = list.City,
                                  ContactNumber1 = list.ContactNumber1,
                                  ContactNumber2 = list.ContactNumber2,
                                  MiddleName = list.MiddleName,
                                  Email = list.Email,
                                  AlternateEmail = list.Email,
                                  DateOfBirth = list.DateOfBirth,
                                  Gender = list.Gender,
                                  IsActive = Convert.ToInt16(list.IsActive),
                                  Image1 = list.Image1,
                                  PermanentAddress = list.PermanentAddress,
                                  Pincode = list.Pincode,
                                  State = list.State,
                                  Password = list.Password,
                                  UserRoleId = (Guid)list.UserRoleId,
                                  EmployeeId = list.EmployeeId,
                                  UserRoleString = role.UserRole
                              }).OrderBy(x => x.IsActive).ToList<EmployeeData>();
                
                
                //return db.GetEmployeeListForActivation(emailId);
            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;
            }
            return result;
        }

        //Completed
        public bool updateEmployee(Guid id, int active, Guid role, string email)
        {
            bool result = false;
            try
            {
                var employee = db.GetEmployeeDataByEmployeeId(id.ToString());
                if (employee != null)
                {
                    if (active != 2)
                    {
                        employee.IsActive = active;
                        employee.UserRoleId = role;
                        db.UpdateEmployee(employee);
                        string message = string.Format("Congratulations {0}\n Your email :{1} has been activated.\n Now you can login with following cridentials.\n Email : {2}\nPassword : {3}", employee.FirstName + " " + employee.LastName, employee.Email, employee.Email, Cryptography.DecryptStringAES(employee.Password, "evincePassword"));
                        string subject = "Account activation email!";
                        LeaveMasterData leaveMaster = db.GetLeaveMasterDataList().Where(x => x.RoleId.Equals(role)).FirstOrDefault();
                        if (leaveMaster != null)
                        {
                            EmployeeLeaveMasterData empLeaveMaster = new EmployeeLeaveMasterData();
                            empLeaveMaster.EmployeeId = id;
                            empLeaveMaster.Sickleave = leaveMaster.Sickleave;
                            empLeaveMaster.PrivilageLeave = leaveMaster.PrivilageLeave;
                            empLeaveMaster.LeaveWithoutPay = leaveMaster.LeaveWithoutPay;
                            empLeaveMaster.CasualLeave = leaveMaster.CasualLeave;
                            empLeaveMaster.Year = leaveMaster.Year;
                            db.CreateEmployeeLeave(empLeaveMaster);
                        }
                        SendMailMethod(employee.Email, Constants.EMAIL_ACTIVATION, subject, message);
                        result = true;
                    }
                    else if (active == 2)
                    {
                        var roleName = db.GetUserRoleDataById(role.ToString());
                        employee.UserRoleId = role;
                        db.UpdateEmployee(employee);
                        string message = string.Format("Dear {0}\n Your Role in our Organization is changed, Now your role is :{1}.", employee.FirstName + " " + employee.LastName, roleName);
                        string subject = "User role changed!";
                        SendMailMethod(employee.Email, Constants.EMAIL_ACTIVATION, subject, message);
                        result = true;
                    }
                }
                //return db.updateEmployee(id,active,role,email);
            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;
            }
            return result;
        
        
        
        }

        //Completed
        public bool GetUpdatedUserProfile(EmployeeData emdata, string email)
        {
            bool result = false;
            try
            {
                var employeeList = db.GetEmployeeDataList();
                if (employeeList != null && emdata!=null)
                {

                    var employee = employeeList.Where(x => x.Email.Equals(email)).FirstOrDefault();
                    #region EmployeeData to Update
                    employee.FirstName = emdata.FirstName;
                    employee.MiddleName = emdata.MiddleName;
                    employee.LastName = emdata.LastName;
                    employee.Email = emdata.Email;
                    employee.AlternateEmail = emdata.AlternateEmail;
                    employee.DateOfBirth = emdata.DateOfBirth;
                    employee.Gender = emdata.Gender;
                    employee.Image1 = emdata.Image1;
                    employee.ContactNumber1 = emdata.ContactNumber1;
                    employee.ContactNumber2 = emdata.ContactNumber2;
                    employee.TemporaryAddress = emdata.TemporaryAddress;
                    employee.PermanentAddress = emdata.PermanentAddress;
                    employee.Pincode = emdata.Pincode;
                    employee.State = emdata.State;
                    employee.City = emdata.City;
                    employee.GCourse = emdata.GCourse;
                    employee.GFrom = emdata.GFrom;
                    employee.GTo = emdata.GTo;
                    employee.GCourseType = emdata.GCourseType;
                    employee.GUniversity = emdata.GUniversity;
                    employee.GCGPA = emdata.GCGPA;
                    employee.PCourse = emdata.PCourse;
                    employee.PFrom = emdata.PFrom;
                    employee.PTo = emdata.PTo;
                    employee.PCourseType = emdata.PCourseType;
                    employee.PUniversity = emdata.PUniversity;
                    employee.PCGPA = emdata.PCGPA;
                    employee.XCourse = emdata.XCourse;
                    employee.XFrom = emdata.XFrom;
                    employee.XTo = emdata.XTo;
                    employee.XCourseType = emdata.XCourseType;
                    employee.XUniversity = emdata.XUniversity;
                    employee.XCGPA = emdata.XCGPA;
                    employee.XIICourse = emdata.XIICourse;
                    employee.XIIFrom = emdata.XIIFrom;
                    employee.XIITo = emdata.XIITo;
                    employee.XIICourseType = emdata.XIICourseType;
                    employee.XIIUniversity = emdata.XIIUniversity;
                    employee.XIICGPA = emdata.XIICGPA; 
                    #endregion
                    db.UpdateEmployee(employee);
                    result = true;
                }
                //return db.GetUpdatedUserProfile(emdata, email);
            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;
            }
            return result;


        }

        //Completed
        public bool GetUpdatePassword(EmployeeData emdata, string email)
        {
            bool result = false;
            try
            {
                var employee = db.GetEmployeeDataList().Where(x => x.Email.Equals(email)).FirstOrDefault();
                if (employee != null)
                {
                    employee.Password = Cryptography.EncryptStringAES(emdata.Password, "evincePassword");
                    result= db.UpdateEmployee(employee);
                }
                //return db.GetUpdatePassword(emdata, email);
            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;
            }

            return result;

        }


        //Completed
        public List<ExperienceData> GetUserExperince(string email)
        {
            List<ExperienceData> result = null;
            try
            {
                var employee = db.GetEmployeeDataList().Where(x => x.Email.Equals(email)).FirstOrDefault();
                if (employee != null)
                {
                    result= db.GetExperienceDataList().Where(x => x.EmployeeId.Equals(employee.ID)).ToList();
                }
                
                
                //return db.GetUserExperince(email);
            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;
            }

            return result;

        }

        //Completed
        public List<AppOptionData> GetAppOption(string email, string key)
        {
            List<AppOptionData> result = null;
            try
            {
                result = db.GetAppOptionDataList().Where(x => x.ParamKey.Equals(key)).ToList();
                //return db.GetAppOption(email, key);
            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;
            }
            return result;
        }

        //Completed
        public bool AddYourExperince(ExperienceData experinceData, string email,string flag, string experinceId)
        {
            bool result = false;
            try
            {
                if (flag == "1")
                {
                    if (!string.IsNullOrEmpty(experinceId))
                    {
                        var experience = db.GetExperinceDataById(experinceId);

                        #region Update experience data
                        experience.EmployerName = experinceData.EmployerName;
                        experience.ContactNumber = experinceData.ContactNumber;
                        experience.Address = experinceData.Address;
                        experience.EmployeementType = experinceData.EmployeementType;
                        experience.EmploymentFrom = experinceData.EmploymentFrom;
                        experience.EmploymentTo = experinceData.EmploymentTo;
                        experience.Designation = experinceData.Designation;
                        experience.AnnualSalary = experinceData.AnnualSalary;
                        experience.Description = experinceData.Description; 
                        #endregion

                       result= db.UpdateExperince(experience);
                    }
                
                
                }
                if (flag != "1")
                {
                    var employeeId = db.GetEmployeeDataList().Where(x => x.Email.Equals(email)).Select(x => x.ID).FirstOrDefault();
                    
                    experinceData.EmployeeId = employeeId;
                    result = db.CreateExperince(experinceData);
                
                
                }





                //return db.AddYourExperince(experinceData,email,flag,experinceId);
            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;
            }


            return result;

        }

        //Completed
        public bool DeleteExperience(string experienceId, string email)
        {
            try
            {
                return db.DeleteExperince(experienceId);
            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;
            }




        }

        //Completed
        public ExperienceData EditExperience(string experienceId, string email)
        {
            try
            {
                return db.GetExperinceDataById(experienceId);
            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;
            }
        }

        //Completed
        public List<ExperienceData> GetExperinceByUserId(string employeeId)
        {
            List<ExperienceData> result = null;
            try
            {

               var experienceList= db.GetExperienceDataList();
               var appOptionList = db.GetAppOptionDataList();
               result = (from list in experienceList
                         where list.EmployeeId.ToString() == employeeId
                         join appOption in appOptionList on list.EmployeementType equals appOption.ParamId
                         select new ExperienceData
                         {
                             ExperienceId = list.ExperienceId,
                             EmployerName = list.EmployerName,
                             ContactNumber = list.ContactNumber,
                             Address = list.Address,
                             EmployeementType = list.EmployeementType,
                             EmploymentFrom = list.EmploymentFrom,
                             EmploymentTo = list.EmploymentTo,
                             Designation = list.Designation,
                             AnnualSalary = list.AnnualSalary,
                             Description = list.Description,
                             EmploymentTypeString = appOption.ParamValue
                         }).ToList<ExperienceData>();  
            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;
            }
            return result;
        }

        //public List<ParentChildData> GetParentChild()
        //{
        //    try
        //    {
        //        return db.GetParentChild();
        //    }
        //    catch (Exception ex)
        //    {
        //        LogEngine.Log(ex.Message);
        //        throw;
        //    }
        //}

        //Completed
        public bool AddGalleryPage(GalleryData gallery)
        {
            try
            {
                return db.InsertGallery(gallery);
            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;
            }
        }

        //Completed
        public bool DeleteGalleryImage(string imageId)
        {
            try
            {
                return db.DeleteGallery(imageId);
            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;
            }
        }


        //Completed
        public bool UpdateGalleryImage(string imageId, string status)
        {
            bool result = false;
            try
            {
                var gallery = db.GetGalleryDataById(imageId);
                if (gallery != null)
                {
                    if (status == "true")
                        gallery.IsActive = 1;
                    else if (status == "false")
                        gallery.IsActive = 0;
                    result = db.UpdateGallery(gallery);               
                
                }
                //return db.UpdateGalleryImage(imageId,status);
            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;
            }
            return result;
        }

        //Completed
        public List<GalleryData> GetGallary(bool flag)
        {
            List<GalleryData> gallerydata = null;
            try
            {
                if (flag == true)
                {
                    gallerydata = db.GetGalleryDataList().Where(x => x.IsActive.Equals(1)).ToList();
                }
                else if (flag == false)
                {
                    gallerydata = db.GetGalleryDataList();
                }
                //return db.GetGallary(flag);
            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;
            }
            return gallerydata;
        }

        //Completed
        public List<UserRoleData> GetAllUserRole(string email)
        {
            try
            {
                return db.GetUserRoleDataList();
            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;
            }
        
        }

        //Completed
        public bool CreateRole(string emailId, string RoleName)
        {
            try
            {
                UserRoleData userRole=new UserRoleData ();
                userRole.UserRole=RoleName;
                return db.InsertUserRole(userRole);
            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;
            }
        }

        //Completed
        public List<EmployeeData> GetOnlineUsers(string emailId)
        {
            List<EmployeeData> onlineUsersList = null;
            try
            {
                var employeeList = db.GetEmployeeDataList().Where(x => x.IsOnline.Equals(true) && x.Email!=emailId.Trim()).ToList();
                onlineUsersList = (from list in employeeList
                                   select new EmployeeData
                                   {
                                       ID = list.ID,
                                       FirstName = list.FirstName,
                                       LastName = list.LastName,
                                       Email = list.Email,
                                       EmployeeFullName = list.FirstName + " " + list.LastName
                                   }).ToList<EmployeeData>();
              //  return db.GetOnlineUsers(emailId);
            }
            catch (Exception ex)
            {
                LogEngine.Log(ex.Message);
                throw;
            }
            return onlineUsersList;
        }



        }



      

    }

